package com.wolf.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wolf.gulimall.product.service.CategoryBrandRelationService;
import com.wolf.gulimall.product.vo.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wolf.common.utils.PageUtils;
import com.wolf.common.utils.Query;

import com.wolf.gulimall.product.dao.CategoryDao;
import com.wolf.gulimall.product.entity.CategoryEntity;
import com.wolf.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.util.comparator.Comparators;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询所有的分类及子分类信息,以树形结构组装返回
     *
     * @return 树形结构分类信息
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //组装父子树形结构

        //找出所有的一级分类
        List<CategoryEntity> levelOneMenus = categoryEntities.stream().filter(categoryEntity ->
                        categoryEntity != null && categoryEntity.getParentCid() == 0)
                .peek(category -> category.setChildren(getChildren(category, categoryEntities)))
                .filter(category1 -> category1.getSort() != null)
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))//排序
                .collect(Collectors.toList());
        return levelOneMenus;
    }

    /**
     * 根据菜单ID批量删除菜单
     *
     * @param ids 菜单ID集合
     */
    @Override
    public void deleteMenuByIds(List<Long> ids) {
        //TODO 检查当前删除的菜单,是否被别的地方引用
        baseMapper.deleteBatchIds(ids);
    }


    /**
     * 根据catLogId 查询出分类信息的完整路径
     *
     * @param catLogId 三级分类ID
     * @return 分类信息的完整路径
     */
    @Override
    public Long[] findCatLogPath(Long catLogId) {
        log.info("进入findCatLogPath方法");
        List<Long> list = new ArrayList<>();
        List<Long> parentPath = findParentPath(list, catLogId);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[0]);
    }

    /**
     * 级联更新所有关联的数据
     *
     * @param category 参数
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCascade(category.getCatId(), category.getName());
    }

    /**
     * 查询所有的一级分类
     *
     * @return 一级分类信息
     */
    //每一个需要缓存的数据,都要指定放到那个名字的缓存[缓存分区的概念(按照业务类型进行分区)]
    @Cacheable(value = {"category"}, key = "#root.method.name") //代表当前方法结果需要进行缓存,如果缓存中有该数据,方法不调用,没有调用该方法,将数据保存到缓存中
    @Override
    public List<CategoryEntity> getLevelOneCategory() {
        log.info("调用getLevelOneCategory方法!");
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }


    /**
     * 查询所有分类信息(从数据库查询数据并封装返回)
     *
     * @return 所有分类信息
     */

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {
       /* String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if (!StringUtils.isEmpty(catalogJson)) {
            //缓存不为空直接返回
            return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
        }
        //查询所有的分类信息
        List<CategoryEntity> categoryEntityS = baseMapper.selectList(null);
        //查出所有一级分类
        List<CategoryEntity> levelOneCategory = getParentByCid(categoryEntityS, 0L);
        //封装数据
        Map<String, List<Catelog2Vo>> map = levelOneCategory.stream().collect(Collectors.toMap(category -> category.getCatId().toString(), category -> {
            //查询二级分类信息
            List<CategoryEntity> categoryEntityList = getParentByCid(categoryEntityS, category.getCatId());
            List<Catelog2Vo> catelog2VoList = null;
            if (categoryEntityList != null && categoryEntityList.size() > 0) {
                catelog2VoList = categoryEntityList.stream().map(categoryEntity -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(category.getCatId().toString(), null, categoryEntity.getCatId().toString(), categoryEntity.getName());
                    //查询三级分类信息
                    List<CategoryEntity> entityList = getParentByCid(categoryEntityS, categoryEntity.getCatId());
                    if (entityList != null && entityList.size() > 0) {
                        List<Catelog2Vo.Category3Vo> category3Vos = entityList.stream()
                                .map(entity -> new Catelog2Vo.Category3Vo(categoryEntity.getCatId().toString(), entity.getCatId().toString(), entity.getName()))
                                .collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2VoList;
        }));
        //3、将查到的数据放入缓存,将对象转为json
        String valueJson = JSON.toJSONString(map);
        redisTemplate.opsForValue().set("catalogJson", valueJson, 1, TimeUnit.DAYS);*/
        return null;
    }

    /**
     * 查询所有分类信息(分布式锁)
     *
     * @return 所有分类信息
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonByCacheRedis() {
        //获取随机值,设置redis枷锁的唯一值
        String uuid = UUID.randomUUID().toString();
        //加分布式锁,并设置锁的过期时间,防止死锁,保证一次只能有一个线程访问共享资源
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (Boolean.TRUE.equals(lock)) {
            System.out.println("获取分布式锁成功!!!");
            Map<String, List<Catelog2Vo>> catalogJsonFromDb;
            try {
                //加锁成功...执行业务
                catalogJsonFromDb = getCatalogJsonFromDb();
            } finally {
                //lua 脚本,原子性执行该脚本
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                //删除锁
                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Collections.singletonList("lock"), uuid);
            }
            return catalogJsonFromDb;
        } else {
            System.out.println("获取分布式锁失败...等待重试...");
            //加锁失败...重试机制
            //休眠一百毫秒
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonByCache();     //类似自旋的方式
        }
    }

    /**
     * 查询所有分类信息(分布式锁 Redisson)
     *
     * @return 所有分类信息
     */
    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJsonByCache() {
        //1、占分布式锁。去redis占坑
        //（锁的粒度，越细越快:具体缓存的是某个数据，11号商品） product-11-lock
        //RLock catalogJsonLock = redissonClient.getLock("catalogJson-lock");
        //创建读锁
//        RReadWriteLock readWriteLock = redisson.getReadWriteLock("catalogJson-lock");
//
//        RLock rLock = readWriteLock.readLock();
//
//        Map<String, List<Catelog2Vo>> dataFromDb = null;
//        try {
//            rLock.lock();
//            //加锁成功...执行业务
//            dataFromDb = getCatalogJsonFromDb();
//        } finally {
//            rLock.unlock();
//        }
//
//        return dataFromDb;
        //查询所有的分类信息
        List<CategoryEntity> categoryEntityS = baseMapper.selectList(null);
        //查出所有一级分类
        List<CategoryEntity> levelOneCategory = getParentByCid(categoryEntityS, 0L);
        //封装数据
        Map<String, List<Catelog2Vo>> map = levelOneCategory.stream().collect(Collectors.toMap(category -> category.getCatId().toString(), category -> {
            //查询二级分类信息
            List<CategoryEntity> categoryEntityList = getParentByCid(categoryEntityS, category.getCatId());
            List<Catelog2Vo> catelog2VoList = null;
            if (categoryEntityList != null && categoryEntityList.size() > 0) {
                catelog2VoList = categoryEntityList.stream().map(categoryEntity -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(category.getCatId().toString(), null, categoryEntity.getCatId().toString(), categoryEntity.getName());
                    //查询三级分类信息
                    List<CategoryEntity> entityList = getParentByCid(categoryEntityS, categoryEntity.getCatId());
                    if (entityList != null && entityList.size() > 0) {
                        List<Catelog2Vo.Category3Vo> category3Vos = entityList.stream()
                                .map(entity -> new Catelog2Vo.Category3Vo(categoryEntity.getCatId().toString(), entity.getCatId().toString(), entity.getName()))
                                .collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2VoList;
        }));
        return map;
    }

    /**
     * 过滤所有的分类信息
     *
     * @param selectList 分类信息
     * @param parentCid  过滤条件
     * @return 过滤后的分类信息
     */
    private List<CategoryEntity> getParentByCid(List<CategoryEntity> selectList, Long parentCid) {
        return selectList.stream().filter(item -> item.getParentCid().equals(parentCid)).collect(Collectors.toList());
    }

    //递归查询子菜单的完整路径
    private List<Long> findParentPath(List<Long> list, Long catLogId) {
        log.info("进入findParentPath方法");
        list.add(catLogId);
        log.info("list{}", list);
        CategoryEntity categoryEntity = this.getById(catLogId);
        log.info("categoryEntity:{}", categoryEntity);
        if (categoryEntity.getParentCid() != 0) {
            findParentPath(list, categoryEntity.getParentCid());
        }
        return list;
    }

    //递归查询所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity category, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> entities = categoryEntities.stream()
                .filter(category1 -> Objects.equals(category1.getParentCid(), category.getCatId()))
                .peek(category1 -> category1.setChildren(getChildren(category1, categoryEntities)))
                .filter(category1 -> category1.getSort() != null)
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());
        return entities;
    }

}